import {useEffect} from 'react';
import {Form, Modal, Input, message} from "antd";
import {createNas, modifyNas} from '@/services/nas'
import {checkData} from '@/tools/tool'

const CreateAndModify = (props: any) => {
  const {visible, mode, onClose, onOk, data} = props
  const [form] = Form.useForm()
  const {TextArea} = Input;
  useEffect(() => {
    if (visible && !!data && mode === 'create') {
      form.resetFields()
    } else {
      form.setFieldsValue({
        nasname: data.nasname,
        shortname: data.shortname,
        nas_type: data.type,
        description: data.description,
      })
    }
  }, [visible, mode, data])
  const handleOk = () => {
    form.validateFields().then(value => {
      if (mode === 'create') {
        createNas({...value}).then(res => {
          if (res.status === 200) {
            onOk()
            message.success(res.message).then()
          } else {
            message.error(res.message).then()
          }
        })
      } else {
        modifyNas({...value, NasId: data.id}).then(res => {
          if (res.status === 200) {
            onOk()
            message.success(res.message).then()
          } else {
            message.error(res.message).then()
          }
        })
      }
    })
  }
  return (
    <Modal
      destroyOnClose
      keyboard={false}
      maskClosable={false}
      closable={false}
      title={mode === 'create' ? '增加NAS' : '修改NAS'}
      visible={visible}
      onCancel={onClose}
      onOk={handleOk}
    >
      <Form form={form} labelCol={{span: 6}} wrapperCol={{span: 14}} autoComplete="off">
        <Form.Item label={'NAS地址'} name="nasname" rules={[{required: true, message: '对接NAS地址必填'}]}>
          <Input/>
        </Form.Item>
        <Form.Item label={'NAS名称'} name="shortname"
                   rules={[{required: true, message: '对接NAS名称必填'}, {validator: checkData}]}>
          <Input/>
        </Form.Item>
        <Form.Item label={'NAS类型'} name="nas_type" rules={[{required: true, message: '对接NAS类型必填'}]}>
          <Input/>
        </Form.Item>
        <Form.Item label={'NAS描述'} name="description"
                   rules={[{required: true, message: '对接NAS描述必填'}, {validator: checkData}]}>
          <TextArea autoSize/>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateAndModify;
